package calculator

import (
	"stock-analyzer/internal/model"
)

// CalculateMaxDrawdown 计算最大回撤
func CalculateMaxDrawdown(data []model.StockData) float64 {
	if len(data) == 0 {
		return 0
	}

	maxDrawdown := 0.0
	peak := data[0].Close

	for i := 1; i < len(data); i++ {
		current := data[i].Close

		// 更新峰值
		if current > peak {
			peak = current
			continue
		}

		// 计算当前回撤
		drawdown := (peak - current) / peak * 100
		if drawdown > maxDrawdown {
			maxDrawdown = drawdown
		}
	}

	return maxDrawdown
}

// CalculateWindowChange 计算指定窗口的涨跌幅
func CalculateWindowChange(data []model.StockData, window int) (float64, bool) {
	if len(data) < window {
		return 0, false
	}

	// 获取窗口起始和结束价格
	startPrice := data[len(data)-window].Close
	endPrice := data[len(data)-1].Close

	// 计算涨跌幅百分比
	change := (endPrice - startPrice) / startPrice * 100
	return change, true
}

// CalculateAllWindowChanges 计算所有指定窗口的涨跌幅
func CalculateAllWindowChanges(data []model.StockData, windows []int) map[int]float64 {
	results := make(map[int]float64)

	for _, window := range windows {
		if change, ok := CalculateWindowChange(data, window); ok {
			results[window] = change
		}
	}

	return results
}

// CheckWindowCondition 检查窗口涨跌幅条件
func CheckWindowCondition(actualChange float64, rule model.WindowChangeRule) bool {
	switch rule.Type {
	case "gt":
		return actualChange > rule.Change
	case "lt":
		return actualChange < rule.Change
	case "ge":
		return actualChange >= rule.Change
	case "le":
		return actualChange <= rule.Change
	default:
		return false
	}
}
